<template>
  <div class="app-container supplier-manage">
    <div>
      <avue-form
        :option="option"
        v-model="queryParams"
        ref="searchForm"
        v-show="showSearch"
        @keydown.enter="getList"
      >
        <template #menu-form>
          <el-button icon="Search" type="primary" @click="getList" class="m-l-3"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleEmpty(searchForm)"
            >重置</el-button
          >
        </template>
      </avue-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAdd"
            >准入申请</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="EditPen"
            @click="handleUpdate"
            :disabled="disUpdate"
            >编辑申请</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="EditPen"
            @click="handleAssess"
            :disabled="disAssess"
            >年度评价</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="EditPen"
            @click="handleChange"
            :disabled="disAssess"
            >信息变更</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="EditPen"
            @click="handleDel"
            :disabled="disDelete"
            >删除</el-button
          >
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="tableList"
        row-key="id"
        :row-class-name="rowClassName"
        @selection-change="handleSelectionChange"
        @row-dblclick="
          row => {
            goTo('/source/sourceModules/supplierDetails', {
              supplierId: row.id,
              proInsId: row.proInsId,
              isCirculation:
                row.approvalStatus === '审批通过' ? true : undefined
            })
          }
        "
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="supplierName" label="供应商名称" />
        <el-table-column
          prop="supplierTaxcode"
          label="统一社会信用代码"
          width="180"
        />
        <el-table-column prop="creditRating" label="信用级别" width="130" />
        <el-table-column prop="expireDate" label="到期时间" width="130" />
        <el-table-column prop="approvalStatus" label="状态" width="130" />
        <el-table-column prop="status" label="来源" width="130">
          <template #default="scope">
            <div>
              <dict-drop :options="supplier_type" :value="scope.row.type" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="首次申请单位" width="130" />
        <el-table-column prop="orgName" label="所属公司" width="130" />
        <el-table-column
          prop="purchaseProduct"
          label="采购我方产品"
          width="130"
        >
          <template #default="scope">
            <div>
              <dict-drop
                v-if="scope.row.purchaseProduct != '1'"
                :options="sys_have_no"
                :value="scope.row.purchaseProduct"
              />
              <div v-else>
                产品:{{ scope.row.productName
                }}<!-- productPrice -->
              </div>
            </div></template
          >
        </el-table-column>
        <!-- <el-table-column prop="status" label="状态" width="130">
          <template #default="scope">
            <div>
              <dict-drop :options="order_status" :value="scope.row.status" />
              <span
                class="text-12px text-#999999"
                v-if="scope.row.approvalStatus"
                >({{ scope.row.approvalStatus }})</span
              >
            </div>
          </template>
        </el-table-column> -->
        <!-- <el-table-column
          label="操作"
          align="center"
          class-name="small-padding"
          min-width="90"
        >
          <template #default="scope">
            <el-button
              plain
              type="primary"
              icon="CircleCheckFilled"
              size="small"
              class="px-11px"
              @click="handleContinue(scope.row)"
              >跟进</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 信息变更对话框 -->
    <el-dialog
      :title="infoBox.title"
      v-model="infoBox.open"
      :width="infoBox.width"
      append-to-body
    >
      <el-form
        ref="infoRef"
        :model="infoForm"
        :rules="infoRules"
        label-width="140px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="供应商名称" prop="alterSupplierName">
              <el-input
                v-model="infoForm.alterSupplierName"
                placeholder="请输入供应商名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开户银行" prop="alterDepositBank">
              <el-input
                v-model="infoForm.alterDepositBank"
                placeholder="请输入开户银行"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="银行账号" prop="alterBankAccount">
              <el-input
                v-model="infoForm.alterBankAccount"
                placeholder="请输入银行账号"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancelInfo">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="SupplierManage">
import { useRouter } from 'vue-router'
import {
  listSupplier,
  setAlterSupplier,
  delSupplier
} from '@/api/supplierManage/index'
import { parseTime } from '@/utils/ruoyi'
import {
  companyOption //归属公司
} from '@/hooks/dict/order'
import useUserStore from '@/store/modules/user'
import { addManage } from '@/api/system/notice'
import useCommonStore from '@/store/modules/common'
const commonStore = useCommonStore()
const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()

const { yes_or_no, sys_have_no, supplier_type } = proxy.useDict(
  'yes_or_no', //是否
  'sys_have_no', //有无
  'supplier_type' //--供应商类型
)

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierName: undefined,
    orgName: userStore.userInfo.orgId,
    supplierTaxcode: undefined,
    expireDate: undefined
  },
  ids: [],
  selectArr: [],
  total: 0,
  option: {
    labelWidth: '10',
    menuSpan: 5,
    submitBtn: false,
    menuPosition: 'left',
    // gutter: 30,
    emptyBtn: false,
    column: [
      {
        prop: 'supplierName',
        span: 3,
        placeholder: '供应商名称',
        type: 'input'
      },
      {
        prop: 'supplierTaxcode',
        span: 3,
        placeholder: '供应商税号',
        type: 'input'
      },
      {
        prop: 'type',
        span: 3,
        placeholder: '供应商来源',
        type: 'select',
        dicData: supplier_type
      },
      {
        prop: 'expireDate',
        type: 'daterange',
        span: 5,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '到期开始时间',
        endPlaceholder: '到期结束时间'
      },
      {
        prop: 'orgName',
        span: 3,
        placeholder: '所属公司',
        type: 'tree',
        defaultExpandAll: true,
        disabled: userStore.userInfo.orgId != 484,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption
      },
      {
        prop: 'expireFlag',
        span: 2,
        placeholder: '是否到期',
        type: 'select',
        dicData: yes_or_no
      }
    ]
  },
  showSearch: true,
  disUpdate: true /* 编辑按钮是否可编辑 */,
  disAssess: true /* 评审是否可编辑 */,
  disDelete: true /* 关闭按钮是否可编辑 */,
  loading: false,
  tableList: [],
  followUpParam: {} // 跟进弹窗配置
})
const {
  queryParams,
  ids,
  selectArr,
  total,
  option,
  showSearch,
  disUpdate,
  disAssess,
  disDelete,
  loading,
  tableList,
  followUpParam
} = toRefs(data)
const tableConfig = [
  // {
  //   show: true,
  //   prop: 'property',
  //   label: '单据属性',
  //   align: 'center',
  //   dict: order_property,
  //   minWidth: 80,
  //   showOverflowTooltip: true
  // },
  {
    show: true,
    prop: 'customerName',
    label: '供应商名称',
    align: 'center',
    minWidth: 150,
    showOverflowTooltip: true
  },
  {
    show: userStore.userInfo.orgId == 484,
    prop: 'orgName',
    label: '所属公司',
    align: 'center',
    minWidth: 80,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'receiptsDate',
    label: '单据日期',
    align: 'center',
    formatter: row => {
      return parseTime(row.receiptsDate, '{y}-{m}-{d}')
    },
    minWidth: 80,
    showOverflowTooltip: true
  },
  {
    show: false,
    prop: 'remark',
    label: '备注',
    align: 'center',
    minWidth: 80,
    showOverflowTooltip: true
  }
]
// 行样式
const rowClassName = ({ row }) => {
  let className = 'cursor-pointer'
  if (row.expireFlag == '1') className = 'row-red cursor-pointer'
  return className
}
// 初始化
async function init() {
  // 归属部门
  getList()
}
// 重置
function handleEmpty(formEl) {
  console.log('queryParams.value1==>', toRaw(queryParams.value))
  proxy.resetForm('searchForm')
  proxy.resetForm('seniorSearchForm')
  // proxy.$refs.searchForm.resetForm()
  getList()
}

// 获取数据列表
function getList() {
  loading.value = true
  console.log('queryParams.value2==>', queryParams.value)
  listSupplier(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
    console.log(' tableList.value==>', tableList.value)
  })
  console.log('获取数据')
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  let approvalUpdate = selectArr.value.some(
    item => item.approvalStatus == '流程未发起'
  )
  let approvalStatus = selectArr.value.some(
    item => item.approvalStatus == '审批通过'
  )
  let dele = selectArr.value.some(
    item => item.createBy !== userStore.userInfo.userName
  )
  let roles =
    userStore.roles.includes('admin') || userStore.roles.includes('swgl')
  disUpdate.value = selection.length != 1 || !approvalUpdate
  disAssess.value = selection.length != 1 || !approvalStatus
  disDelete.value = !selection.length || roles ? false : dele
}
function goTo(url, data) {
  router.push({ path: url, query: data })
}
function handleAdd() {
  goTo('/source/sourceModules/supplierForm', {})
}
function handleDownload() {}
function handleUpdate() {
  goTo('/source/sourceModules/editSupplier', {
    supplierId: ids.value[0]
  })
}
// 年度评价
function handleAssess() {
  goTo('/source/sourceModules/evaluateForm', {
    salesOrderData: JSON.stringify({ id: ids.value[0] })
  })
}

//打开跟进弹窗
function handleContinue(row) {
  console.log('跟进==》', followUpParam.value)
  /***订单模块 */
  console.log('row==>', row)
  followUpParam.value.isVisible = true
  followUpParam.value.tableName = 'ord_inner_order'
  followUpParam.value.businessId = row.id
  followUpParam.value.customer = row.customerName
  followUpParam.value.orderName = row.title
}

const infoBox = reactive({
  title: '供方信息变更',
  open: false,
  width: '900'
})
const infoForm = ref({})
const infoRules = ref({
  supplierName: [
    {
      required: true,
      message: '请输入供应商名称',
      trigger: 'blur'
    }
  ]
})
// 信息变更
const handleChange = () => {
  proxy.resetForm('infoRef')
  infoBox.open = true
}
// 确认
const submitForm = async () => {
  const infoId = await commonStore.getUploadTemplateDown(
    'supplier_info_approver'
  )
  if (
    !infoForm.value.alterBankAccount &&
    !infoForm.value.alterDepositBank &&
    !infoForm.value.alterSupplierName
  )
    return proxy.$message.error('请输入变更供应商信息')
  infoForm.value.id = ids.value[0]
  infoForm.value.alterFlag = '0'
  proxy.$refs['infoRef'].validate(valid => {
    if (valid) {
      setAlterSupplier(infoForm.value).then(res => {
        let mesVoData = {
          businessId: '供应商信息变更_' + new Date().getTime(), //业务ID
          content: '您接收到新的供应商信息变更', //待办内容
          followDate: undefined, //跟进日期
          followType: undefined, //跟进方式
          impSign: '2', //重要程度:0-非常重要，1-重要，2-一般
          receiver: infoId, //接收人 只有娜姐
          receiverName: undefined, //接收人中文
          reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
          sendTime: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'), //发送时间
          sender: useUserStore().user.nickName, //发送人
          serviceType: '20', //业务类型:0-项目，1-订单，2-客户，3-工单，4-任务，5-产品，6-合同，7-公告，8-日程，9-回款, 10-联系人
          title: '您接收到新的供应商信息变更', //待办标题
          type: undefined, //待办类型:0-普通，1-流程
          urgFlag: '2', //紧急程度:0-非常紧急，1-紧急，2-一般
          url: `/source/sourceModules/supplierDetails?supplierId=${infoForm.value.id}`, //待办链接(多链接用英文逗号隔开)
          urlName: '前往处理' //待办链接名称(多链接名称用英文逗号隔开)
        }
        addManage(mesVoData)
        proxy.$modal.msgSuccess('信息已提交')
        cancelInfo()
      })
    }
  })
}
const cancelInfo = () => {
  infoBox.open = false
}

// 删除
function handleDel(row) {
  // let rowIds = row.id
  let supplierName = selectArr.value.map(item => item.supplierName)
  proxy
    .$confirm(`是否将“${supplierName.toString()}”从列表中删除`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      delSupplier(ids.value.toString()).then(() => {
        getList()
        proxy.$message({
          type: 'success',
          message: '移出成功!'
        })
      })
    })
    .catch(() => {})
}

init()
</script>
<style scoped>
.search-drawer-retract {
  color: #999999;
}
.supplier-manage :deep(.row-red) {
  @apply bg-red-100 !important;
}
</style>
